import 'package:dio/dio.dart';
import 'dart:convert';
import 'package:sharing/utils/whole_apis.dart';
import 'package:sharing/utils/dio_singleton_manager.dart';
import 'package:sharing/model/origin_article.dart';
import 'package:sharing/net/ris_read_apis.dart';
class NetUtil {
  static const String GET = "get";
  static const String POST = "post";

    // post 方式请求
  static void originPost(String url , Options opt , Function callback){
    Dio().post(url, options: opt,data: opt.data).then((value){callback(value);});
  }

//   get 方式请求
  static void originGet(String url , Options opt, Function callback){
    Dio().get(url,options: opt).then((value){callback(value);});
  }

  static void createNewBookList(Function callback ,[Options opt,]){
    String url =WholeApis.hostName + RisReadApis.establishBookList;
    Dio().post(url,options: opt,data: opt.data).then((value){
      callback(value);
    });
  }
  // 获取原创的书籍
  static void getOriginWork(Function callback, int _page,
      [Options _opt]) async {
    String url = WholeApis.originUrl + '/$_page';
    print("url is ${url} ${_opt != null? _opt.headers : "null"}");

    Dio().get(url, options: _opt).then((response) {
      try {
        print("data ${response.data}");
        if (response.data == null){
          return ;
        }
        callback(OriginArticle.fromJson(json.decode(response.data)));
      } catch (e) {
        print("error : " + e.toString());
      }
    });
  }

  // 获取推荐的书籍
  static void getRecommend(Function callback, [Options _opt]) {
    String url = WholeApis.recommendBookUrl;
    print("recommend url ${url}");
    DioSingletonManager.singleton.dio.get(url, options: _opt).then((response) {
      try {
        callback(OriginArticle.fromJson(response.data));
      } catch (e) {
        print("error : " + e.toString());
      }
    });
  }

  //get请求
  static void get(String url, Function callBack,
      {Map<String, String> params, Function errorCallBack}) async {
    _request(url, callBack,
        method: GET, params: params, errorCallBack: errorCallBack);
  }

  //post请求
  static void post(String url, Function callBack,
      {Map<String, String> params, Function errorCallBack}) async {
    _request(url, callBack,
        method: POST, params: params, errorCallBack: errorCallBack);
  }

  //具体的还是要看返回数据的基本结构
  //公共代码部分
  static void _request(String url, Function callBack,
      {String method,
      Map<String, String> params,
      Function errorCallBack}) async {
    print("<net> url :<" + method + ">" + url);

    if (params != null && params.isNotEmpty) {
      print("<net> params :" + params.toString());
    }

    String errorMsg = "";
    int statusCode;
    Response response;
    try {
      if (method == GET) {
        //组合GET请求的参数
        if (params != null && params.isNotEmpty) {
          StringBuffer sb = new StringBuffer("?");
          params.forEach((key, value) {
            sb.write("$key" + "=" + "$value" + "&");
          });
          String paramStr = sb.toString();
          paramStr = paramStr.substring(0, paramStr.length - 1);
          url += paramStr;
        }
        response = await Dio().get(url);
      } else {
        if (params != null && params.isNotEmpty) {
          //print("par${params}");
          response = await Dio().post(url,
              data: params,
              options: Options(headers: {'Content-Type': 'application/json'}));
        } else {
          response = await Dio().post(url);
        }
      }


      //  ...
      statusCode = response.statusCode;

      //处理错误部分
      if (statusCode < 0) {
        errorMsg = "网络请求错误,状态码:" + statusCode.toString();
        _handError(errorCallBack, errorMsg);
        return;
      }
      print("${response.headers['authorization']}");
      if (callBack != null) {
        // callBack(response);
        response.data['authorization'] = response.headers['authorization'][0];
        print("response ${response.data}");
        callBack(json.encode(response.data));
      }
    } catch (exception) {
      print("我遇到了一个错误 ${response}");
      _handError(errorCallBack, exception.toString());
    }
  }

  //处理异常
  static void _handError(Function errorCallback, String errorMsg) {
    if (errorCallback != null) {
      errorCallback(errorMsg);
    }
    print("<net> errorMsg :" + errorMsg);
  }
}
